package com.dhq.myapp.util.ask
import android.util.Log
import org.json.JSONObject
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

/**
 * token的获取类
 * 将apiKey和secretKey换取token，注意有效期保存在expiresAt
 */
class TokenHolder(private val apiKey: String, private val secretKey: String, private val scope: String?) {
    companion object {
        const val TTS_SCOPE = "audio_tts_post"

        /**
         * url , Token的url，http可以改为https
         */
        private const val url = " http://aip.baidubce.com/oauth/2.0/token"
    }

    /**
     * asr的权限 scope 是  "audio_voice_assistant_get"
     * tts 的权限 scope 是 "audio_tts_post"
     */

    /**
     * 保存访问接口获取的token
     */
    private var token: String = ""

    /**
     * 当前的时间戳，毫秒
     */
    private var expiresAt: Long = 0

    /**
     * 获取token，refresh 方法后调用有效
     */
    fun getToken(): String = token

    /**
     * 获取过期时间，refresh 方法后调用有效
     */
    fun getExpiresAt(): Long = expiresAt

    /**
     * 获取token
     * @throws IOException   http请求错误
     * @throws DemoException http接口返回不是 200, access_token未获取
     */
    @Throws(IOException::class, DemoException::class)
    fun resfresh() {
        val getTokenURL = "$url?grant_type=client_credentials" +
                "&client_id=${ConnUtil.urlEncode(apiKey)}&client_secret=${ConnUtil.urlEncode(secretKey)}"

        // 打印的url出来放到浏览器内可以复现
//        println("token url:$getTokenURL")
        Log.e("token url", getTokenURL)
        val url = URL(getTokenURL)
        val conn = url.openConnection() as HttpURLConnection
        conn.connectTimeout = 5000
        val result = ConnUtil.getResponseString(conn)
//        println("Token result json:$result")
        parseJson(result)
    }

    /**
     * @param result token接口获得的result
     * @throws DemoException
     */
    @Throws(DemoException::class)
    private fun parseJson(result: String) {
        val json = JSONObject(result)
        if (!json.has("access_token")) {
            // 返回没有access_token字段
            throw DemoException("access_token not obtained, $result")
        }
        if (!json.has("scope")) {
            // 返回没有scope字段
            throw DemoException("scopenot obtained, $result")
        }
        // scope = null, 忽略scope检查
        if (scope != null && !json.getString("scope").contains(scope)) {
            throw DemoException("scope not exist, $scope,$result")
        }
        token = json.getString("access_token")
        expiresAt = System.currentTimeMillis() + json.getLong("expires_in") * 1000
    }
}